package pemks.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Date;

/**
 * @description:  
 * @author kl
 * @date 2025/4/4 下午9:57
 * @version 1.0
 */
@WebFilter("/*")
public class AuthFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("Authorization");

//        if (requiresAuth(req) && !validateToken(token)) {
//            ((HttpServletResponse)response).sendError(401, "Unauthorized");
//            return;
//        }
        chain.doFilter(request, response);
    }

    private boolean requiresAuth(HttpServletRequest req) {
        return !req.getRequestURI().contains("/login")
                && !req.getRequestURI().contains("/register");
    }


    private boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("your-secret-key")
                    .parseClaimsJws(token)
                    .getBody();

            // 检查过期时间
            Date expiration = claims.getExpiration();
            return expiration.after(new Date());
        } catch (ExpiredJwtException ex) {
            System.out.println("Token已过期");
            return false;
        } catch (Exception e) {
            System.out.println("无效Token");
            return false;
        }
    }
}
